package org.sc.learn.server.auth.entity;

import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.hibernate.annotations.BatchSize;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;

import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
import javax.persistence.Transient;
import java.util.HashSet;
import java.util.Set;

/**
 * @author qianwx
 */
@Entity
@Table(name = "t_auth_user")
@Data
@EqualsAndHashCode
public class User extends AbstractAuditingEntity {
  private static final long serialVersionUID = 486674012931863780L;

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private long id;

  private String username;

  private String password;

  private String firstName;

  private String lastName;

  private String email;

  private String imageUrl;

  @JsonIgnore
  @ManyToMany(targetEntity = Role.class, fetch = FetchType.EAGER)
  @BatchSize(size = 20)
  private Set<Role> roles = new HashSet<>();

  @Transient
  private Set<GrantedAuthority> authorities;

  public Set<GrantedAuthority> getAuthorities() {
    Set<GrantedAuthority> authorities = new HashSet<>();
    roles.stream().forEach(role -> {
      role.getAuthorities().stream().forEach(authority ->
              authorities.add(new SimpleGrantedAuthority(authority.getValue())));
    });
    return authorities;
  }
}
